﻿using System;
using System.IO;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace MyVocabulary.Popup
{
    public partial class RenameFile : Form
    {
        #region Const

        protected static class FormMessages
        {
            public const string InvalidNameErrorMsg = "Please enter a valid name";
            public const string GeneralErrorMsg = "Error renaming file";
        }

        #endregion

        protected string fileName;

        public FileInfo NewFileName { get; set;}
        public event EventHandler OnFileRenamed;

        public RenameFile(string fileName)
        {
            this.fileName = fileName;
            InitializeComponent();
            tbName.Text = new Regex("(\\.xml$)|(\\.vml$)").Replace((new FileInfo(fileName)).Name, string.Empty);
        }

        private void btnOk_Click(object sender, EventArgs e)
        {            
            if(tbName.Text.Length == 0)
            {
                lbError.Text = FormMessages.InvalidNameErrorMsg;
                toolTip1.SetToolTip(lbError, FormMessages.InvalidNameErrorMsg);
                return;                
            }

            try
            {
                var file = new FileInfo(fileName);
                file.MoveTo(string.Format("{0}\\{1}{2}", file.DirectoryName, tbName.Text, file.Extension));
                NewFileName = file;

                if (OnFileRenamed != null)
                    OnFileRenamed(this, null);
                Close();
            }
            catch (Exception exp)
            {
                lbError.Text = FormMessages.GeneralErrorMsg;
                toolTip1.SetToolTip(lbError,exp.Message);
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            Close();
        }
    }
}